package com.zr.sms.daoimpl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.zr.sms.dao.FuncDao;
import com.zr.sms.util.JDBCUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


public class FuncDaoImpl implements FuncDao{


	public JSONArray getfuncsByParentId(int parentId,String rfuncs) {
		JSONArray funcs=new JSONArray();
		Connection con=null;
		PreparedStatement stmt=null;
		ResultSet rs=null;
		con=JDBCUtil.getConnection();
		StringBuffer sql=new StringBuffer("select * from func where parentId=?");
		
	        String[]rfuncss=rfuncs.split(",");
		    int fids[]=new int[rfuncss.length];
		    for (int i = 0; i < fids.length; i++) {
				fids[i]=Integer.parseInt(rfuncss[i]);
			}
		    
		try {
			stmt=con.prepareStatement(sql.toString());
			stmt.setInt(1, parentId);
			rs=stmt.executeQuery();
			while (rs.next()) {
				for (int i = 0; i < fids.length; i++) {
					if(rs.getInt("fid")==fids[i]){
						JSONObject func =new JSONObject();
						if(rs.getString("fstate").equals("close")){
							func.put("iconCls", "icon-folder");
						}else{
							func.put("iconCls", "icon-file");
						}
						func.put("id", rs.getInt("fid"));
						func.put("text",rs.getString("fname"));
						func.put("state",rs.getString("fstate"));
						JSONObject atrr=new JSONObject();
						atrr.put("fpath", rs.getString("fpath"));
						func.put("attributes", atrr);
						funcs.add(func);
					}
				}
				
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return funcs;
	}


	public JSONArray getCurrentUserFuncsByParentId(int parentId,String rfuncs) {
		JSONArray funcs=this.getfuncsByParentId(parentId,rfuncs);
		for (int i = 0; i < funcs.size(); i++) {
			String fstate=funcs.getJSONObject(i).getString("state");
			if("open".equals(fstate)){
				continue;
			}else{
				int currentFid=funcs.getJSONObject(i).getInt("id");
		        JSONArray childrenFuncs= this.getCurrentUserFuncsByParentId(currentFid,rfuncs);
		        funcs.getJSONObject(i).put("children", childrenFuncs);
			}
			
		}
		
		return funcs;
	}

	
}
